package cn.com.huzo.service.trade.impl;

import cn.com.huzo.model.entities.trade.MasterProductionScheduleLinesEntity;
import cn.com.huzo.model.entities.trade.MasterProductionScheduleLinesTrackEntity;
import huzofw.service.impl.GenericManagerImpl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.collections4.MapUtils;
import cn.com.huzo.repository.trade.MasterProductionScheduleHeaderRepository;
import cn.com.huzo.repository.trade.MasterProductionScheduleLinesRepository;
import cn.com.huzo.repository.trade.MasterProductionScheduleLinesTrackRepository;
import cn.com.huzo.service.trade.MasterProductionScheduleLinesManager;

/**
 * 产品计划明细管理服务对象类实现。
 *
 * @author 吴旭
 */
@Service("MasterProductionScheduleLinesManager")
public class MasterProductionScheduleLinesManagerImpl extends GenericManagerImpl<MasterProductionScheduleLinesEntity, String>
        implements MasterProductionScheduleLinesManager {

    @Resource(name = "MasterProductionScheduleHeaderRepository")
    private MasterProductionScheduleHeaderRepository _dao_header;

    @Resource(name = "MasterProductionScheduleLinesRepository")
    private MasterProductionScheduleLinesRepository _dao_lines;

    @Resource(name = "MasterProductionScheduleLinesTrackRepository")
    private MasterProductionScheduleLinesTrackRepository _dao_lines_track;

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    public List<MasterProductionScheduleLinesEntity> fetchLinesByHeaderKey(Long headerId) throws Exception {
        return _dao_lines.fetchByHeaderKey(headerId);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> insertLines(List<MasterProductionScheduleLinesEntity> itemList) throws Exception {
        Integer rowsAffected = _dao_lines.batchInsert(itemList);
        if (rowsAffected > 0) {
            // 审计日志
            for (int i = 0; i < itemList.size(); i++) {
                MasterProductionScheduleLinesEntity instance = itemList.get(i);
                writeAuditLog(itemList.get(0).getUpdatedBy(), "贸易信息→产品计划明细", "款号：" + instance.getStyleNo() + "　颜色：" + instance.getProductColour(), "增加");
            }
        }

        Map<String, Object> rtnValue = new HashMap();
        // 为了得到系列号
        rtnValue.put("HeaderEntity", _dao_header.fetchByKey(itemList.get(0).getHeaderId(), itemList.get(0).getUpdatedBy(), itemList.get(0).getWorkFlowId()));
        rtnValue.put("LinesList", _dao_lines.fetchByHeaderKey(itemList.get(0).getHeaderId()));
        return rtnValue;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Integer updateLines(List<MasterProductionScheduleLinesEntity> itemList) throws Exception {
        Integer rowsAffected = _dao_lines.batchUpdate(itemList);
        // 做计划项目跟踪
        itemList.stream().forEach((instance) -> {
            // 根据明细标识删除计划项目跟踪
            _dao_lines_track.deleteByParentLinesId(instance.getLinesId());
            // 插入计划项目跟踪
            if (instance.getTrackSchemaList() != null && !instance.getTrackSchemaList().isEmpty()) {
                _dao_lines_track.insert(instance.getTrackSchemaList());
            }
        });
        // 审计日志
        for (int i = 0; i < itemList.size(); i++) {
            MasterProductionScheduleLinesEntity instance = itemList.get(i);
            writeAuditLog(itemList.get(0).getUpdatedBy(), "贸易信息→产品计划明细",
                    "款号：" + instance.getStyleNo() + "　颜色：" + instance.getProductColour(), "更新");
        }

        return rowsAffected;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public List<MasterProductionScheduleLinesEntity> updateLinesForSync(MasterProductionScheduleLinesEntity instance) throws Exception {
        _dao_lines.updateLinesForSync(instance);
        return _dao_lines.fetchByHeaderKey(instance.getHeaderId());
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> delete(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();
        // 删除
        Integer rowsAffected = _dao_lines.delete(MapUtils.getString(criterion, "LinesId"));
        if (rowsAffected > 0) {
            // 审计日志
            writeAuditLog(MapUtils.getLong(criterion, "DeletedBy"),
                    "贸易信息→产品计划明细", "明细数据（" + MapUtils.getString(criterion, "LinesData") + "）",
                    "删除");
        }
        _result.put("LinesList", _dao_lines.fetchByHeaderKey(MapUtils.getLong(criterion, "HeaderId")));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public List<MasterProductionScheduleLinesEntity> syncUpdateTrackItem(List<MasterProductionScheduleLinesTrackEntity> itemList) throws Exception {
        // 做计划项目跟踪
        itemList.stream().forEach((instance) -> {
            // 根据明细标识删除计划项目跟踪
            _dao_lines_track.syncUpdateTrackItem(instance.getHeaderId(),
                    instance.getParentLinesId(), instance.getItemId(),
                    instance.getPlan(), instance.getActual(), instance.getStatus(), instance.getUpdatedBy());
        });

        return _dao_lines.fetchByHeaderKey(itemList.get(0).getHeaderId());
    }
}
